package pro.cherish.smartfile.config.exception;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import org.reactivestreams.Publisher;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import pro.cherish.smartfile.common.response.Result;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * @author lys
 */
@Component
public class JsonHttpMessageWriter implements HttpMessageWriter<Map<String, Object>> {
    @NonNull
    @Override
    public List<MediaType> getWritableMediaTypes() {
        return Collections.singletonList(MediaType.APPLICATION_JSON_UTF8);
    }

    @Override
    public boolean canWrite(@NonNull ResolvableType elementType, MediaType mediaType) {
        return MediaType.APPLICATION_JSON.includes(mediaType);
    }

    @NonNull
    @Override
    public Mono<Void> write(@NonNull Publisher<? extends Map<String, Object>> inputStream,
                            @NonNull ResolvableType elementType,
                            MediaType mediaType,
                            @NonNull ReactiveHttpOutputMessage message,
                            @NonNull Map<String, Object> hints) {
        return Mono.from(inputStream).flatMap(m -> message.writeWith(Mono.just(message.bufferFactory().wrap(transform2Json(m).getBytes()))));
    }

    /**
     * 仅仅是做一些默认值处理，以及JSON格式化，并且以自定义的result的格式作为返回
     *
     * @param sourceMap
     * @return
     */
    private String transform2Json(Map<String, Object> sourceMap) {
        String code = ObjectUtil.defaultIfNull(sourceMap.getOrDefault("code", "200"), "").toString();
        String msg = ObjectUtil.defaultIfNull(sourceMap.getOrDefault("msg", ""), "").toString();
        return JSON.toJSONString(Result.error(code, msg));
    }
}
